﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;

namespace Camelot.SharePointIntegration.Client
{
    public static class Extensions
    {
        public static byte[] DeflateCompress(this string data)
        {
            using (var memoryStream = new MemoryStream())
            {
                using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
                {
                    using (var streamWriter = new StreamWriter(deflateStream))
                    {
                        streamWriter.Write(data);
                    }
                }
                return memoryStream.ToArray();
            }
        }
        
        public static string DeflateDecompress(this byte[] data)
        {
            using (var memoryStream = new MemoryStream(data))
            {
                using (var deflateStream = new DeflateStream(memoryStream, CompressionMode.Decompress))
                {
                    using (var streamReader = new StreamReader(deflateStream))
                    {
                        return streamReader.ReadToEnd();
                    }
                }
            }
        }

        public static string MD5(this string value)
        {
            var provider = new MD5CryptoServiceProvider();
            var byteArray = provider.ComputeHash(Encoding.UTF8.GetBytes(value));

            string result = "";
            foreach (byte b in byteArray)
            {
                result += b.ToString("x2");
            }
            return result;
        }

        internal static string XmlDecodeName(this System.Xml.XmlNode node)
        {
            return System.Xml.XmlConvert.DecodeName(node.Name);
        }
    }
}
